//
//  DZMReadMenu.swift
//  DZMeBookRead
//
//  Created by 邓泽淼 on 2017/5/11.
//  Copyright © 2017年 DZM. All rights reserved.
//

/// 翻页类型
enum CLEffectType:Int, Codable {
    case none = 0               // 无效果
    case translation = 1        // 平移
    case simulation = 2         // 仿真
    init(index:Int) {
        if index == 1 {
            self = .translation
        } else if index == 2 {
            self = .simulation
        } else {
            self = .none
        }
    }
}

/// 字体类型
enum CLFontType:Int, Codable {
    case system = 0             // 系统
    case one = 1                // 楷体
    case two = 2                // 宋体
    init(index:Int) {
        if index == 1 {
            self = .one
        } else if index == 2 {
            self = .two
        } else {
            self = .system
        }
    }
}

import UIKit
import ASValueTrackingSlider

@objc protocol DZMReadMenuDelegate:NSObjectProtocol {
    
    /// 状态栏 将要 - 隐藏以及显示状态改变
    @objc optional func readMenuWillShowOrHidden(readMenu:DZMReadMenu, isShow:Bool)
    
    /// 状态栏 完成 - 隐藏以及显示状态改变
    @objc optional func readMenuDidShowOrHidden(readMenu:DZMReadMenu, isShow:Bool)
    
    /// 点击下载
    @objc optional func readMenuClickDownload(readMenu:DZMReadMenu)
    
    /// 点击返回按钮
    @objc optional func readMenuClickBackButton(readMenu:DZMReadMenu, button:UIButton)
    
    
    /// 点击更多按钮
    @objc optional func readMenuClickMoreButton(readMenu:DZMReadMenu, button:UIButton)
    
    /// 点击上一章（上一话）
    @objc optional func readMenuClickPreviousChapter(readMenu:DZMReadMenu)
    
    /// 点击下一章（下一话）
    @objc optional func readMenuClickNextChapter(readMenu:DZMReadMenu)
    
    /// 停止滚动进度条
    @objc optional func readMenuSliderEndScroll(readMenu:DZMReadMenu,slider:ASValueTrackingSlider)
    
    /// 点击背景颜色
    @objc optional func readMenuClickSetuptColor(readMenu:DZMReadMenu,index:NSInteger,color:UIColor)
    
    /// 点击翻书动画
    @objc optional func readMenuClickSetuptEffect(readMenu:DZMReadMenu,index:NSInteger)
    
    /// 点击字体
    @objc optional func readMenuClickSetuptFont(readMenu:DZMReadMenu,index:NSInteger)
    
    /// 点击字体大小
    @objc optional func readMenuClickSetuptFontSize(readMenu:DZMReadMenu,fontSize:CGFloat)
    
    /// 点击日间夜间
    @objc optional func readMenuClickLightButton(readMenu:DZMReadMenu,isDay:Bool)
    
    /// 点击章节列表
    @objc optional func readMenuClickChapterList(readMenu:DZMReadMenu,index:Int)
    
}

class DZMReadMenu: NSObject,UIGestureRecognizerDelegate {
    
    /// 控制器
    private(set) weak var vc:CLReadViewController!
    
    /// 代理
    private(set) weak var delegate:DZMReadMenuDelegate!
    
    /// 阅读页面动画的时间
    private var animateDuration:TimeInterval = 0.20
    
    /// 菜单显示
    private(set) var menuShow:Bool = false
    
    /// 单击手势
    private(set) var singleTap:UITapGestureRecognizer!
    
    /// LeftView
    private var leftView:DZMRMLeftView?
    
    /// TopView
    private(set) var topView:DZMRMTopView!
    
    /// BottomView
    private(set) var bottomView:DZMRMBottomView!
    
    /// 遮盖亮度
    private lazy var coverView = UIView()
    
    /// 小说阅读设置
    private var novelsSettingView:DZMRMSettingView!
    
    /// NovelsSettingView 高
    private var novelsSettingViewH:CGFloat {
        if UIScreen.main.bounds.height == 812.0
            || UIScreen.main.bounds.height == 896.0 {
            return 278.0 + 34.0 + 60.0
        } else {
            return 278.0 + 60.0
        }
    }
    
    /// 初始化
    static func readMenu(vc:CLReadViewController,delegate:DZMReadMenuDelegate) -> DZMReadMenu {
        let readMenu = DZMReadMenu(vc:vc,delegate:delegate)
        return readMenu
    }
    
    /// 初始化函数
    private init(vc:CLReadViewController,delegate:DZMReadMenuDelegate) {
        
        super.init()
        
        // 记录
        self.vc = vc
        self.delegate = delegate
        
        // 隐藏状态栏
        UIApplication.shared.setStatusBarHidden(!self.menuShow, with: .fade)
        
        // 允许获取电量信息
        UIDevice.current.isBatteryMonitoringEnabled = true
        
        // 添加手势
        self.initTapGestureRecognizer()
        
        // 创建UI
        self.creatUI()
        
        // 初始化数据
        self.initData()
    }
    
    /// 创建UI
    private func creatUI() {
        
        // 初始化TopView
        self.initTopView()
        
        // 初始化BottomView
        self.initBottomView()
    
        // 初始化NovelsSettingView
        self.initNovelsSettingView()
        
        // 初始化LeftView
        self.initLeftView()
        
        // 初始化遮盖亮度
        self.initCoverView()
        
    }
    
    /// 初始化数据
    func initData() {
        // 进度条数据初始化
        self.bottomView.sliderUpdate()
    }
    
    // MARK: -- TapGestureRecognizer
    
    /// 初始化TapGestureRecognizer
    private func initTapGestureRecognizer() {
    
        // 单击手势
        singleTap = UITapGestureRecognizer(target: self, action: #selector(DZMReadMenu.touchSingleTap))
        singleTap.numberOfTapsRequired = 1
        singleTap.delegate = self
        vc.view.addGestureRecognizer(singleTap)
    }
    
    // 触发单击手势
    @objc private func touchSingleTap() {
        
        menuSH()
    }
    
    // MARK: -- UIGestureRecognizerDelegate
    
    /// 点击这些控件不需要执行手势
    private let ClassString:[String] = ["ASValueTrackingSlider","UITableViewCellContentView","UITableView","UISlider","CJBookReader.DZMRMLeftView","CJBookReader.DZMRMTopView","CJBookReader.DZMRMBottomView","CJBookReader.DZMHaloButton","CJBookReader.DZMRMLightView","CJBookReader.DZMRMColorView","CJBookReader.DZMRMFuncView","CJBookReader.DZMSettingView","UIButton"]

    /// 手势拦截
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        let classString = NSStringFromClass(touch.view!.classForCoder)
 
        if ClassString.contains(classString) {
            return false
        }
        
        return true
    }
    
    // MARK: -- LeftView
    
    /// 初始化LeftView
    private func initLeftView() {
        self.leftView = DZMRMLeftView(readMenu:self)
        self.leftView?.isHidden = true
        self.leftView?.backgroundColor = UIColor.clear
        self.leftView?.addTarget(self, action: #selector(self.clickLeftView), for: .touchUpInside)
        self.vc.view.addSubview(self.leftView!)
        self.leftView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
    }
    
    /// 点击事件
    @objc private func clickLeftView() {
        self.leftView(isShow: false, complete: nil)
    }
    
    // MARK: -- SettingView
    
    /// 初始化NovelsSettingView
    private func initNovelsSettingView() {
        self.novelsSettingView = DZMRMSettingView(frame:CGRect(x: 0, y: UIScreen.main.height, width: UIScreen.main.width, height: self.novelsSettingViewH),readMenu:self)
        self.novelsSettingView.isHidden = true
        self.vc.view.addSubview(self.novelsSettingView)
    }
    
    // MARK: -- CoverView
    
    /// 初始化CoverView
    private func initCoverView() {
        
        self.coverView.isUserInteractionEnabled = false
        
        self.coverView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        
        self.coverView.alpha = CLReadConfigure.shared.isNight ? 1.0 : 0
        
        self.vc.view.addSubview(self.coverView)
        
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    // MARK: -- TopView
    
    /// 初始化TopView
    private func initTopView() {
        self.topView = DZMRMTopView(readMenu:self)
        self.topView.setTitle(self.vc.record?.chapter?.name)
        self.topView.isHidden = !self.menuShow
        self.vc.view.addSubview(self.topView)
        self.topView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            // 适配iPhoneX
            if UIScreen.main.bounds.height == 812.0
                || UIScreen.main.bounds.height == 896.0 {
                make.height.equalTo(88.0)
            } else {
                make.height.equalTo(64.0)
            }
        }
        
    }
    
    ///跳转充值
    func recharge(chIndex:Int?=nil,pageIndex:Int?=nil) {
        
    }
    
    func jumpLogin() {
        
    }
    
    // MARK: -- BottomView
    private func initBottomView() {
        self.bottomView = DZMRMBottomView(readMenu:self)
        self.bottomView.isHidden = !self.menuShow
        self.vc.view.addSubview(self.bottomView)
        self.bottomView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    // MARK: -- 展示 Func
    
    /// 动画是否完成
    private var isAnimateComplete = true
    
    /// 菜单 show hidden
    func menuSH() {
        self.menuSH(isShow: !self.menuShow)
        self.bottomView.sliderUpdate()
    }
    
    /// 菜单 show hidden
    func menuSH(isShow:Bool) {
        if self.isAnimateComplete { UIApplication.shared.setStatusBarHidden(!isShow, with: .fade) }
        self.menu(isShow: isShow)
    }
    
    /// 总控制
    private func menu(isShow:Bool) {
        
        if self.menuShow == isShow || !self.isAnimateComplete { return }
        self.isAnimateComplete = false
        self.menuShow = isShow
        
        // 将要动画
        self.delegate?.readMenuWillShowOrHidden?(readMenu: self, isShow: self.menuShow)
        self.bottomView(isShow: isShow, complete:nil)
        self.novelsSettingView(isShow: false, complete:nil)
        self.topView(isShow: isShow) { [weak self] ()->Void in
            guard let weakSelf = self else { return }
            self?.isAnimateComplete = true
            // 完成动画
            self?.delegate?.readMenuDidShowOrHidden?(readMenu: weakSelf, isShow: weakSelf.menuShow)
        }
    }
    
    /// LeftView 展示
    func leftView(isShow:Bool,complete:(()->Void)?) {
        
        guard let leftMenu = self.leftView, leftMenu.isHidden != !isShow else { return }
        
        if isShow {
            self.leftView?.isHidden = false
            
            //如果选中的是章节
            if leftMenu.topView.selectIndex == 0 {
                leftMenu.chapterTableView.reloadData()
                //定位到当前章节
                let chapters = self.vc.book.chapters
                let currentChapter = self.vc.record?.chapter
                if let index = chapters.firstIndex(where: { (item) -> Bool in
                    return item.id == currentChapter?.id
                }) {
                    let indexPath = IndexPath(row: index, section: 0)
                    self.leftView?.chapterTableView.scrollToRow(at: indexPath, at: .middle, animated: false)
                }
            } else {
                self.leftView?.markTableView.reloadData()
            }
        }
        
        self.leftView?.contentView.snp.remakeConstraints { (make) in
            if isShow {
                make.left.equalToSuperview()
            } else {
                make.right.equalTo(leftMenu.snp.left)
            }
            make.width.equalTo(leftMenu.snp.width).multipliedBy(0.7)
            if UIScreen.main.bounds.height == 812.0
                || UIScreen.main.bounds.height == 896.0 {
                make.top.equalToSuperview().offset(44.0)
                make.bottom.equalToSuperview().offset(-34.0)
            } else {
                make.top.equalToSuperview()
                make.bottom.equalToSuperview()
            }
        }
        
        UIView.animate(withDuration: animateDuration, animations: { [weak self] ()->Void in
            
            self?.leftView?.layoutIfNeeded()
            
            if isShow {
                self?.leftView?.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            } else {
                
                self?.leftView?.backgroundColor = UIColor.clear
            }
            
        }) {[weak self] (isOK) in
            
            if !isShow {self?.leftView?.isHidden = true}
            
            if complete != nil {complete!()}
        }
    }
    
    /// TopView 展示
    func topView(isShow:Bool,complete:(()->Void)?) {
        
        if self.topView.isHidden == !isShow {return}
        
        self.topView.superview?.layoutIfNeeded()
        
        if isShow {
            self.topView.isHidden = false
            self.topView.snp.updateConstraints { (make) in
                make.top.equalToSuperview()
            }
        } else {
            self.topView.snp.updateConstraints { (make) in
                var topViewHeight:CGFloat = 64.0
                if UIScreen.main.bounds.height == 812.0
                    || UIScreen.main.bounds.height == 896.0 {
                    topViewHeight = 88.0
                }
                make.top.equalToSuperview().offset(-topViewHeight)
            }
        }
       
        UIView.animate(withDuration: self.animateDuration, animations: { [weak self] ()->Void in
            self?.topView.superview?.layoutIfNeeded()
        }) {[weak self] (isOK) in
            if !isShow {
                self?.topView.isHidden = true
            }
            complete?()
        }
    }
    
    /// BottomView 展示
    func bottomView(isShow:Bool,complete:(()->Void)?) {
        
        if self.bottomView.isHidden == !isShow {return}
        
        self.bottomView.superview?.layoutIfNeeded()
        
        if isShow {
            self.bottomView.isHidden = false
            self.bottomView.snp.updateConstraints { (make) in
                make.bottom.equalToSuperview()
            }
        } else {
            self.bottomView.snp.updateConstraints { (make) in
                make.bottom.equalToSuperview().offset(150.0)
            }
        }
        
        UIView.animate(withDuration: self.animateDuration, animations: { [weak self] ()->Void in
            self?.bottomView.superview?.layoutIfNeeded()
        }) {[weak self] (isOK) in
            if !isShow {self?.bottomView.isHidden = true}
            if complete != nil {complete!()}
        }
    }
    
    /// NovelsSettingView 展示
    func novelsSettingView(isShow:Bool,complete:(()->Void)?) {
        
        if self.novelsSettingView.isHidden == !isShow {return}
        
        if isShow { self.novelsSettingView.isHidden = false}
        
        UIView.animate(withDuration: self.animateDuration, animations: { [weak self] ()->Void in
            if isShow {
                self?.novelsSettingView.frame = CGRect(x: 0, y: UIScreen.main.height - self!.novelsSettingViewH, width: UIScreen.main.width, height: self!.novelsSettingViewH)
            } else {
                self?.novelsSettingView.frame = CGRect(x: 0, y: UIScreen.main.height, width: UIScreen.main.width, height: self!.novelsSettingViewH)
            }
            
        }) {[weak self] (isOK) in
            
            if !isShow {self?.novelsSettingView.isHidden = true}
            
            if complete != nil {complete!()}
        }
    }
}
